package com.codeoss.framework.view.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.codeoss.framework.context.YunContext;
import com.codeoss.framework.expression.Expression;
import com.codeoss.framework.expression.IScriptServiceStore;
import com.codeoss.framework.view.component.Component;
import com.codeoss.framework.view.component.FilterGroup;
import com.codeoss.framework.view.service.IFilterGroupComponentService;

@Service("filtergroupComponentService")
public class FilterGroupComponentService extends ComponentService implements IFilterGroupComponentService {
	@Autowired
	private IScriptServiceStore scriptServiceStore;

	@Override
	public List<Map<String, String>> getFilterList(YunContext yunContext, Component component) {
		// TODO Auto-generated method stub
		FilterGroup filterGroup=(FilterGroup)component;
		Expression dataSourceScript=filterGroup.getDataSourceScript();
		Map<String,Object> bindingMap=new HashMap<String,Object>();
		List<Map<String,String>> dataList=new ArrayList<Map<String,String>>();
		bindingMap.put("filterGroupDataSource", dataList);
		scriptServiceStore.getScriptService(dataSourceScript).eval(dataSourceScript.getScript(), bindingMap);
		return dataList;
	}

	@Override
	public void processEvent(YunContext yunContext, Component component, String eventType) {
		// TODO Auto-generated method stub
		FilterGroup filterGroup=(FilterGroup)component;
		if ("selectedChangeEvent".equals(eventType)) {
			Expression onSelectedChangeExpression = filterGroup.getOnSelectedChangeExpression();
			if (onSelectedChangeExpression != null) {
				executeEventExpression(yunContext, component, onSelectedChangeExpression,null);
			}
		}
	}

	@Override
	public String getSelectedValue(YunContext yunContext, Component component) {
		// TODO Auto-generated method stub
		List<Map<String, String>> mapList=getFilterList(yunContext, component);
		int index=0;
		if(yunContext.isPostBack()) {
			String sIndex=yunContext.getViewRequest().getData().get(component.getId()+"_active");
			index=Integer.parseInt(sIndex);
		}
		String value=mapList.get(index).get("value");
		return value;
	}
}
